// #ifdef H5
let jweixin = require('./jweixin-module')
// #endif

//判断是否在微信中
export const isWechat = () => {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/micromessenger/i) == 'micromessenger') {
        console.log('是微信客户端')
        return true
    } else {
        console.log('不是微信客户端')
        return false
    }
}

// 解析链接
export const getUrlParam = (name) => {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    let url = window.location.href.split('#')[0]
    let search = url.split('?')[1]
    if (search) {
        let r = search.substr(0).match(reg)
        if (r !== null) {
            console.log('截取code', unescape(r[2]))
            return unescape(r[2])
        }
        return null
    } else {
        return null
    }
}

export const pay = (result, pay_type, success, fail) => {
    // 发起微信支付
    if (pay_type == 'wxpay') {
        // #ifdef MP-WEIXIN
        uni.requestPayment({
            provider: 'wxpay',
            timeStamp: result.data.paybody.timeStamp,
            nonceStr: result.data.paybody.nonceStr,
            package: result.data.paybody.package,
            signType: result.data.paybody.signType,
            paySign: result.data.paybody.paySign,
            success: () => {
                paySuccess(result, success)
            },
            fail: () => {
                payError(result, fail)
            },
        })
        // #endif

        // #ifdef H5
        if (isWechat()) {
            wxH5Pay(result, success, fail)
        } else {
            paySuccess(result, success, fail)
        }
        // #endif

        // #ifdef APP-PLUS
        wxAppPay(result, success, fail)
        // #endif
    }

    // 余额支付
    if (pay_type == 'lcnpay') {
        paySuccess(result, success)
    }

    // 支付宝支付
    if (pay_type == 'alipay') {
        // #ifdef APP-PLUS
        aliAppPay(result, success, fail)
        // #endif
        // #ifdef H5
        const div = document.createElement('div')
        div.innerHTML = result.data.paybody
        document.body.appendChild(div)
        document.forms[0].submit()
        document.forms[0].parentNode?.removeChild(document.forms[0])
        // #endif
    }
}

/*支付成功*/
function paySuccess(result, success) {
    if (success) {
        success(result)
        return
    }
    uni.$u.route({
        type: 'back',
    })
}

/*支付失败*/
function payError(result, fail) {
    if (fail) {
        fail(result)
        return
    }
    uni.$u.route({
        type: 'back',
    })
}

const wxH5Pay = (result, success, fail) => {
    jweixin.config({
        debug: false,
        appId: result.data.paybody.appId,
        timestamp: result.data.paybody.timestamp,
        nonceStr: result.data.paybody.nonceStr,
        signature: result.data.paybody.signature,
        jsApiList: ['chooseWXPay'],
    })
    jweixin.ready(() => {
        jweixin.chooseWXPay({
            timestamp: result.data.paybody.timeStamp,
            nonceStr: result.data.paybody.nonceStr,
            package: result.data.paybody.package,
            signType: result.data.paybody.signType,
            paySign: result.data.paybody.paySign,
            success: () => {
                paySuccess(result, success)
            },
            cancel: () => {
                payError(result, fail)
            },
            fail: () => {
                payError(result, fail)
            },
        })
    })
}

function wxAppPay(result, success, fail) {
    // 获取支付通道
    plus.payment.getChannels(
        function (channels) {
            uni.showLoading({
                title: '加载中',
            })
            uni.requestPayment({
                provider: 'wxpay',
                orderInfo: result.data.paybody,
                success(res) {
                    setTimeout(() => {
                        uni.hideLoading()
                    }, 1000)
                    paySuccess(result, success)
                },
                fail(error) {
                    uni.hideLoading()
                    console.log('fail:' + JSON.stringify(error))
                    payError(error, fail)
                },
            })
        },
        function (e) {
            console.log('获取支付通道失败：' + e.message)
        }
    )
}

function aliAppPay(result, success, fail) {
    uni.showLoading({
        title: '加载中',
    })
    uni.requestPayment({
        provider: 'alipay',
        orderInfo: result.data.paybody,
        success(res) {
            setTimeout(() => {
                uni.hideLoading()
            }, 1000)
            paySuccess(result, success)
        },
        fail(error) {
            uni.hideLoading()
            console.log('fail:' + JSON.stringify(error))
            payError(error, fail)
        },
    })
}
